<script setup lang="ts">
import { onMounted, reactive, ref } from "vue";
import api from "@/api";
import {
  type MachineDTO,
  MachineTunnelPageQry,
  type MachineTunnelDTO,
  type PageDTO
} from "@/types";
import "@/assets/base-list.scss";
import "@/assets/form.scss";
import { ElMessage } from "element-plus";
import MachineTunnelSave from "./MachineTunnelSave.vue";
import { useDelete } from "@/hooks";
import { MachineSelect } from "@/components/business";

const saveRef = ref<InstanceType<typeof MachineTunnelSave>>();

interface State {
  loading: boolean;
  qry: MachineTunnelPageQry;
  result: PageDTO<MachineTunnelDTO>;
}

const state = reactive<State>({
  loading: false,
  qry: new MachineTunnelPageQry(),
  result: {
    data: [],
    totalSize: 0,
    current: 1,
    size: 10,
    totalPage: 0
  }
});

const loadData = () => {
  state.loading = true;
  api.machineTunnel
    .getMachineTunnelPage(state.qry)
    .then((res) => {
      state.result = res.data;
    })
    .finally(() => {
      state.loading = false;
    });
};

const reset = () => {
  state.qry = new MachineTunnelPageQry();
  loadData();
};

const handleStart = (row: MachineTunnelDTO) => {
  api.machineTunnel.startMachineTunnel(row.id).then((res) => {
    ElMessage.success(res.message);
    loadData();
  });
};

const handleStop = (row: MachineTunnelDTO) => {
  api.machineTunnel.stopMachineTunnel(row.id).then((res) => {
    ElMessage.success(res.message);
    loadData();
  });
};

const handlePageSizeChange = () => {
  state.qry.current = 1;
  loadData();
};

const handleDelete = (row: MachineDTO) => {
  useDelete(() => api.machineTunnel.deleteMachineTunnel(row.id)).then(loadData);
};

const handleOpenUrl = (ip: string, port: number, protocol: string) => {
  let url = protocol + "://" + ip + ":" + port;
  window.open(url);
};

onMounted(() => {
  loadData();
});
</script>

<template>
  <el-form
    :model="state.qry"
    :inline="true"
    label-width="110px"
    class="crm-content__search overwrite-form"
  >
    <div class="crm-content__search__condition">
      <div class="crm-content__search__condition__main">
        <el-form-item label="主机：" class="el-form-item-width">
          <machine-select
            v-model="state.qry.machineId"
            @change="loadData"
            placeholder="请选择"
            clearable
          />
        </el-form-item>
        <el-form-item label="名称：" class="el-form-item-width">
          <el-input v-model="state.qry.nameLike" @keydown.enter="loadData" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="类型：" class="el-form-item-width">
          <el-select v-model="state.qry.type" @change="loadData" placeholder="请选择" clearable>
            <el-option label="本地" :value="1"></el-option>
            <el-option label="远程" :value="2"></el-option>
            <el-option label="动态" :value="3"></el-option>
          </el-select>
        </el-form-item>
      </div>
    </div>
    <div class="crm-content__search__control">
      <el-button type="primary" @click="loadData" icon="Search"> 查询 </el-button>
      <el-button @click="reset" icon="Refresh"> 重置 </el-button>
    </div>
  </el-form>
  <div p-2>
    <el-button type="primary" @click="saveRef?.openDialog()">新建</el-button>
  </div>

  <el-table flex-1 :data="state.result.data"
            border
            stripe
            resizable
            style="width: 100%" v-loading="state.loading">
    <el-table-column type="index" width="50" label="#"></el-table-column>
    <el-table-column prop="name" label="名称"></el-table-column>
    <el-table-column prop="machineName" label="主机"></el-table-column>
    <el-table-column prop="type" label="类型">
      <template #default="scope">
        {{ scope.row.type === 1 ? "本地" : scope.row.type === 2 ? "远程" : "动态" }}
      </template>
    </el-table-column>
    <el-table-column prop="localIp" label="本地IP"></el-table-column>
    <el-table-column prop="localPort" label="本地端口">
      <template #default="scope">
        <div v-if="scope.row.type === 1 && scope.row.start">
          <el-popover placement="bottom" title="快速访问" :width="200" trigger="click">
            <template #default>
              <div>
                <el-link
                  type="primary"
                  @click="handleOpenUrl('127.0.0.1', scope.row.localPort, 'https')"
                  >https</el-link
                >
              </div>
              <div>
                <el-link
                  type="primary"
                  @click="handleOpenUrl('127.0.0.1', scope.row.localPort, 'http')"
                  >http</el-link
                >
              </div>
            </template>
            <template #reference>
              <el-link type="primary">{{ scope.row.localPort }}</el-link>
            </template>
          </el-popover>
        </div>
        <div v-else>
          {{ scope.row.localPort }}
        </div>
      </template>
    </el-table-column>
    <el-table-column prop="remoteIp" label="远程IP">
      <template #default="scope">
        {{ scope.row.type === 1 ? scope.row.remoteIp : "-" }}
      </template>
    </el-table-column>
    <el-table-column prop="remotePort" label="远程端口">
      <template #default="scope">
        <div v-if="scope.row.type === 2 && scope.row.start">
          <el-popover placement="bottom" title="快速访问" :width="200" trigger="click">
            <template #default>
              <div>
                <el-link
                  type="primary"
                  @click="handleOpenUrl(scope.row.machine.ip, scope.row.remotePort, 'https')"
                  >https</el-link
                >
              </div>
              <div>
                <el-link
                  type="primary"
                  @click="handleOpenUrl(scope.row.machine.ip, scope.row.remotePort, 'http')"
                  >http</el-link
                >
              </div>
            </template>
            <template #reference>
              <el-link type="primary">{{ scope.row.remotePort }}</el-link>
            </template>
          </el-popover>
        </div>
        <div v-else>
          {{ scope.row.type === 1 || scope.row.type === 2 ? scope.row.remotePort : "-" }}
        </div>
      </template>
    </el-table-column>
    <el-table-column prop="start" label="状态">
      <template #default="scope">
        <el-tag v-if="scope.row.start" type="success">已启动</el-tag>
        <el-tag v-else type="danger">未启动</el-tag>
      </template>
    </el-table-column>
    <el-table-column min-width="200" label="操作">
      <template #default="scope">
        <el-button
          type="primary"
          v-if="!scope.row.start"
          size="small"
          @click="handleStart(scope.row)"
        >
          启动
        </el-button>
        <el-button
          type="warning"
          v-if="scope.row.start"
          size="small"
          @click="handleStop(scope.row)"
        >
          停止
        </el-button>
        <el-button
          size="small"
          :disabled="scope.row.start"
          @click="saveRef?.openDialog(scope.row.id)"
        >
          编辑
        </el-button>
        <el-button
          type="danger"
          size="small"
          :disabled="scope.row.start"
          @click="handleDelete(scope.row)"
          >删除</el-button
        >
      </template>
    </el-table-column>
  </el-table>
  <el-pagination
    size="small"
    background
    layout="total, prev, pager, next, sizes, jumper"
    :total="state.result.totalSize"
    v-model:page-size="state.qry.size"
    v-model:current-page="state.qry.current"
    @update:current-page="loadData"
    @update:page-size="handlePageSizeChange"
    p-5
  />
  <machine-tunnel-save ref="saveRef" @success="loadData" />
</template>

<style lang="scss" scoped></style>
